package des.wangku.operate.standard.subengineering;

import java.net.Proxy;

import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import des.wangku.operate.standard.swt.table.ResultTable;
import des.wangku.operate.standard.task.InterfaceThreadRunUnit;
import des.wangku.operate.standard.utls.UtilsConstsRequestHeader;
import des.wangku.operate.standard.utls.UtilsReadURL;
import des.wangku.operate.standard.utls.UtilsString;
import des.wangku.operate.standard.utls.UtilsVerification;

/**
 * 从百度中查关键字，每条记录中是否含有指定网址，得到第一个位置<br>
 * 建立日期:2021-04-19 用于替换 BaiduKeySearchPosid
 * @author Sunjian
 * @version 1.0
 * @since jdk1.8
 */
public class BaiduSearchKeyCheckUrlPosid {
	/** 日志 */
	static Logger logger = LoggerFactory.getLogger(BaiduSearchKeyCheckUrlPosid.class);
	public static final String NoFindNull = "--";
	/** 最多页数 */
	public static int MaxPage = 10;
	/** timeout 超时 */
	public static int Timeout = 20000;
	/** 多个url间隔符 */
	public static String UrlInterval = "|";
	/** 是否判断总站网址，判断是否含有 www.99114.com或.99114.com */
	public static boolean IsCentralUrl = false;
	/** 百度检索线程暂时 */
	public static long BaiduSleepTime = 1000;

	/**
	 * url 必须 为 "abc.99114.com" 不能有协议与空格，并已截取
	 * 得到baidu中的排名 如没检索到，则返回-1<br>
	 * 如检索到，则返回第N条 以0为第1条
	 * @param key String
	 * @param url String
	 * @return String
	 */
	public static final int getBaiduPosidPc(String key, String url) {
		return getBaiduPosid("www", key, url);
	}
	/**
	 * url 必须 为 "abc.99114.com" 不能有协议与空格，并已截取
	 * 得到baidu中的排名 如没检索到，则返回-1<br>
	 * 如检索到，则返回第N条 以0为第1条
	 * @param key String
	 * @param url String
	 * @return String
	 */
	public static final int getBaiduPosidMobi(String key, String url) {
		return getBaiduPosid("m", key, url);
	}
	/** 设置默认代理服务器 */
	public static Proxy DefaultProxy = null;
	/**
	 * url 必须 为 "abc.99114.com" 不能有协议与空格，并已截取
	 * 得到baidu中的排名 如没检索到，则返回-1<br>
	 * 如检索到，则返回第N条 以0为第1条
	 * @param type String
	 * @param key String
	 * @param url String
	 * @return String
	 */
	public static final int getBaiduPosid(String type, String key, String url) {
		return getBaiduPosid(DefaultProxy, type,  key, url,UrlInterval,MaxPage,Timeout,IsCentralUrl,BaiduSleepTime);
	}
	/**
	 * url 必须 为 "abc.99114.com" 不能有协议与空格，并已截取
	 * 得到baidu中的排名 如没检索到，则返回-1<br>
	 * 如检索到，则返回第N条 以0为第1条
	 * @param proxy Proxy
	 * @param type String
	 * @param key String
	 * @param url String
	 * @param urlInterval String
	 * @param maxPage int
	 * @param timeout int
	 * @param isCentralUrl boolean
	 * @param baiduSleepTime long
	 * @return int
	 */
	public static final int getBaiduPosid(Proxy proxy,String type, String key, String url,String urlInterval,int maxPage,int timeout,boolean isCentralUrl,long baiduSleepTime) {
		int maxbaiduPage = (maxPage - 1) * 10;
		if (key == null || key.length() == 0) return -1;
		if (url == null || url.length() == 0) return -1;
		String newUrl = url;
		//if (cutUrl > 0 && cutUrl <= newUrl.length()) newUrl = newUrl.substring(0, cutUrl);
		int p = -1;
		StringBuilder sb = new StringBuilder(50);
		String baiduUrlHref = null;
		for (int i = 0; i <= maxbaiduPage; i += 10) {
			sb.setLength(0);
			sb.append("https://");
			sb.append(type);
			sb.append(".baidu.com/s?wd=");
			sb.append(key);
			sb.append("&pn=");
			sb.append(i);
			baiduUrlHref = sb.toString();
			logger.debug("search:" + baiduUrlHref);
			try {
				if (baiduSleepTime > 0) Thread.sleep(baiduSleepTime);
				Connection connect = Jsoup.connect(baiduUrlHref).timeout(timeout).maxBodySize(0).headers(UtilsConstsRequestHeader.getRndHeadMap());//UtilsConsts.header_m);
				if (proxy != null) {
					connect.proxy(proxy);
					logger.debug("proxy:"+proxy.toString());
				}else {
					connect.proxy(null);
					logger.debug("proxy:null");
				}
				Document document = connect.get();
				if (document == null) {
					logger.debug("document:null");
					continue;
				}
				if (!UtilsString.isContainSplit(document.html().toLowerCase(), newUrl, urlInterval)) {
					p += 10;
					continue;
				}
				logger.debug("document:well");
				Elements es = document.select(".result");
				String searchurl = "";
				for (int x = 0; x < es.size(); x++) {
					logger.debug("document:well"+p);
					Element e = es.get(x);
					p++;
					if (!UtilsString.isContainSplit(e.html().toLowerCase(), newUrl, urlInterval)) continue;
					Elements showurl = e.getElementsByClass("c-showurl");
					Elements as = showurl.select("a[href]");
					for (Element t1 : as) {
						String baiduUrl = t1.attr("abs:href");
						searchurl = UtilsReadURL.getRealLocation(baiduUrl);
						String newurl = searchurl.toLowerCase();
						if (isCentralUrl) {
							if (newurl.indexOf("www.99114.com") == -1 && newurl.indexOf(".99114.com") > -1) { return p; }
						} else {
							if (newurl.indexOf(url) > -1) { return p; }
						}
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return p;
	}

	/**
	 * 把百度排行数量转成 第P页第N条 样式 否则返回null
	 * @param posid int
	 * @return String
	 */
	public static final String getBaiduPosidString(int posid) {
		if (posid < 0) return null;
		int p = posid / 10 + 1;
		int x = posid % 10 + 1;
		return "第" + p + "页第" + x + "条";
	}
	/**
	 * 得到某列的结果，总数与结果总数(排除没有结果数量)
	 * @param table ResultTable
	 * @param x1 int
	 * @param x2 int
	 * @param y int
	 * @return float[]
	 */
	public static final float[] getReusltTable(ResultTable table, int x1, int x2, int y) {
		float[] result = { 0, 0 };
		int count = 0, well = 0;
		for (int i = x1; i <= x2; i++) {
			String value = table.get(i, y);
			if (value == null || value.length() == 0) continue;
			if (UtilsVerification.isNumeric(value)) {
				well++;
				count++;
				continue;
			}
			if (value.equals(NoFindNull)) count++;
		}
		result[0] = count;
		result[1] = well;
		return result;
	}/**
	 * 百度关键字搜索排名单元<br>
	 * 大于0位置，如果没空或没找到，则返回"--"
	 * @author Sunjian
	 * @version 1.0
	 * @since jdk1.8
	 */
	public static class BaiduWorkClass implements InterfaceThreadRunUnit {
		ResultTable rt=null;
		String type;
		String keyword;
		String url;
		int x;
		int y;
		String value=NoFindNull;
		
		String urlInterval=UrlInterval;
		int maxPage =MaxPage;
		int timeout = Timeout;
		long baiduSleepTime = BaiduSleepTime;
		boolean isCentralUrl = IsCentralUrl;
		public BaiduWorkClass(ResultTable rt,String type,String keyword,String url,int x,int y) {
			this.rt=rt;
			this.type = type;
			this.keyword = keyword;
			this.url = url;
			this.x=x;
			this.y=y;
		}
		@Override
		public void run() {
			int p=BaiduSearchKeyCheckUrlPosid.getBaiduPosid(DefaultProxy, type,  keyword, url,urlInterval,maxPage,timeout,isCentralUrl,baiduSleepTime);
			if (p > -1) value = "" + (p + 1);
		}

		@Override
		public void show() {
			if(rt!=null && x>=0 && y>=0)rt.update(x, y, value);
		}

		public long getSleepTime() {
			return timeout;
		}
		@Override
		public String getKeyword() {
			return keyword;
		}
		public final void setUrlInterval(String urlInterval) {
			this.urlInterval = urlInterval;
		}
		public final void setMaxPage(int maxPage) {
			this.maxPage = maxPage;
		}
		public final void setTimeout(int timeout) {
			this.timeout = timeout;
		}
		public final void setBaiduSleepTime(long baiduSleepTime) {
			this.baiduSleepTime = baiduSleepTime;
		}
		public final void setCentralUrl(boolean isCentralUrl) {
			this.isCentralUrl = isCentralUrl;
		}
		
	}

}
